package com.gdpu.liou.symphonyserver.controller;


import com.alibaba.fastjson.JSONObject;
import com.gdpu.liou.symphonyserver.entity.Consumer;
import com.gdpu.liou.symphonyserver.service.ConsumerService;
import com.gdpu.liou.symphonyserver.common.utils.Consts;
import com.gdpu.liou.symphonyserver.common.utils.PagingUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author liou
 */
@Slf4j
@RestController
@RequestMapping(value = "/consumer")
public class ConsumerController {
    private final ConsumerService consumerService;

    public ConsumerController(ConsumerService consumerService) {
        this.consumerService = consumerService;
    }


    /**
     * 根据主键查询整个对象
     */
    @RequestMapping(value = "/selectByPrimaryKey", method = RequestMethod.GET)
    public Object selectByPrimaryKey(HttpServletRequest request) {
        String id = request.getParameter("id");
        if (id == null || "null".equals(id)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "请先登录");
            return jsonObject;
        }
        return consumerService.selectByPrimaryKey(Integer.parseInt(id));
    }


    /**
     * 添加用户
     */
    @RequestMapping(value = "/addConsumer", method = RequestMethod.POST)
    public Object addConsumer(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String sex = request.getParameter("sex");
        String phoneNum = request.getParameter("phoneNum");
        String email = request.getParameter("email");
        String birth = request.getParameter("birth");
        String introduction = request.getParameter("introduction");
        String location = request.getParameter("location");
        String avatar = request.getParameter("avatar");
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "用户名或密码不能为空");
            return jsonObject;
        }
        Consumer consumer1 = consumerService.selectConsumerByName(username);
        if (consumer1 != null) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "用户名已存在");
            return jsonObject;
        }
        Consumer consumer = new Consumer();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //把生日转换成Date格式
        if (!StringUtils.isEmpty(birth)) {
            try {
                dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date birthDate = new Date();
                birthDate = dateFormat.parse(birth);
                consumer.setBirth(birthDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            Date birthDate = new Date();
            try {
                birthDate = dateFormat.parse(birth);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            consumer.setBirth(birthDate);
        }
        consumer.setUsername(username);
        consumer.setPassword(password);
        if (StringUtils.isEmpty(avatar)) {
            if ("1".equals(sex)) {
                avatar = "/default/boy.png";
            } else if ("0".equals(sex)) {
                avatar = "/default/girl.png";
            }
        }
        consumer.setAvatar(avatar);
        if (!StringUtils.isEmpty(sex)) {
            consumer.setSex(new Byte(sex));
        }
        consumer.setPhoneNum(phoneNum);
        consumer.setEmail(email);
        consumer.setIntroduction(introduction);
        consumer.setLocation(location);

        boolean flag = consumerService.insertConsumer(consumer);
        if (flag) {
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "注册成功");
            return jsonObject;
        }
        jsonObject.put(Consts.CODE, 0);
        jsonObject.put(Consts.MSG, "注册失败");
        return jsonObject;
    }


    /**
     * 查询用户分页数据
     */
    @RequestMapping(value = "/pagingQueryConsumer", method = RequestMethod.GET)
    public PagingUtil pagingQuerySinger(Integer currentPage, String username) {
        if (currentPage == null || currentPage == 0) {
            currentPage = 1;
        }
        return consumerService.pagingQueryConsumer(currentPage, username);
    }


    /**
     * 用户登录
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object login(@RequestParam String username, @RequestParam String password) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isEmpty(username)) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "用户名不能为空");
            return jsonObject;
        }
        if (StringUtils.isEmpty(password)) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "密码不能为空");
            return jsonObject;
        }
        Consumer consumer = new Consumer();
        consumer.setUsername(username);
        consumer.setPassword(password);
        boolean flag = consumerService.verifyPassword(username, password);
        if (flag) {
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "登录成功");
            jsonObject.put("userMsg", consumerService.getByUsername(username));
            return jsonObject;
        }
        jsonObject.put(Consts.CODE, 0);
        jsonObject.put(Consts.MSG, "用户名或密码错误");
        return jsonObject;
    }

    /**
     * 修改前端用户
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object updateConsumer(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String sex = request.getParameter("sex");
        String phoneNum = request.getParameter("phoneNum");
        String email = request.getParameter("email");
        String birth = request.getParameter("birth");
        String introduction = request.getParameter("introduction");
        String location = request.getParameter("location");
        if (username == null || username.equals("")) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "用户名不能为空");
            return jsonObject;
        }
        if (password == null || password.equals("")) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "密码不能为空");
            return jsonObject;
        }
        //保存到前端用户的对象中
        Consumer consumer = new Consumer();
        consumer.setId(Integer.parseInt(id));
        consumer.setUsername(username);
        consumer.setPassword(password);
        if(!StringUtils.isEmpty(sex)){
            consumer.setSex(new Byte(sex));
        }
        consumer.setPhoneNum(phoneNum);
        consumer.setEmail(email);
        if(!StringUtils.isEmpty(birth)){
            //把生日转换成Date格式
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date birthDate = new Date();
            try {
                birthDate = dateFormat.parse(birth);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            consumer.setBirth(birthDate);
        }

        consumer.setIntroduction(introduction);
        consumer.setLocation(location);
        boolean flag = consumerService.update(consumer);
        if (flag) {   //保存成功
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "修改成功");
            return jsonObject;
        }
        jsonObject.put(Consts.CODE, 0);
        jsonObject.put(Consts.MSG, "修改失败");
        return jsonObject;
    }


    /**
     * 更新前端用户图片
     */
    
    @RequestMapping(value = "/updateConsumerPic", method = RequestMethod.POST)
    public Object updateConsumerPic(@RequestParam("file") MultipartFile avatarFile, @RequestParam("id") int id) {
        JSONObject jsonObject = new JSONObject();
        if (avatarFile.isEmpty()) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "文件上传失败");
            return jsonObject;
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = System.currentTimeMillis() + avatarFile.getOriginalFilename();
        //文件路径
        String filePath = null;
        try {
            filePath = ResourceUtils.getURL("classpath:").getPath() + "static/avatar";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        //存储到数据库里的相对文件地址
        String storeAvatarPath = "/avatar/" + fileName;
        try {
            avatarFile.transferTo(dest);
            Consumer consumer = new Consumer();
            consumer.setId(id);
            consumer.setAvatar(storeAvatarPath);
            boolean flag = consumerService.update(consumer);
            if (flag) {
                jsonObject.put(Consts.CODE, 1);
                jsonObject.put(Consts.MSG, "上传成功");
                jsonObject.put("avatar", storeAvatarPath);
                return jsonObject;
            }
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "上传失败");
            return jsonObject;
        } catch (IOException e) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "上传失败" + e.getMessage());
        } finally {
            return jsonObject;
        }
    }

    /**
     * 删除用户
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public Object deleteConsumer(HttpServletRequest request) {
        String id = request.getParameter("id");
        boolean flag = consumerService.deleteConsumer(Integer.parseInt(id));
        JSONObject jsonObject = new JSONObject();
        if (flag) {
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "删除成功");
            return jsonObject;
        }
        jsonObject.put(Consts.CODE, 0);
        jsonObject.put(Consts.MSG, "删除失败");
        return jsonObject;
    }

}
